package com.sqx.modules.taking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserBrowseDao;
import com.sqx.modules.app.dao.UserCertificationDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserCertification;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.service.UserBrowseService;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.service.UserVipService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.evaluate.service.SysEvaluateService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.search.service.AppSearchService;
import com.sqx.modules.taking.dao.GameDao;
import com.sqx.modules.taking.dao.OrderTakingCommentDao;
import com.sqx.modules.taking.dao.OrderTakingDao;
import com.sqx.modules.taking.entity.Game;
import com.sqx.modules.taking.entity.OrderTaking;
import com.sqx.modules.taking.response.*;
import com.sqx.modules.taking.service.OrderTakingService;
import com.sqx.modules.task.dao.HelpTakeDao;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderTakingServiceImpl extends ServiceImpl<OrderTakingDao, OrderTaking> implements OrderTakingService {

    @Autowired
    private UserCertificationDao userCertificationDao;
    @Autowired
    private OrderTakingDao orderTakingDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private AppSearchService appSearchService;
    @Autowired
    private GameDao gameDao;
    @Autowired
    private UserBrowseService userBrowseService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private HelpTakeDao helpTakeDao;
    @Autowired
    private UserBrowseDao userBrowseDao;
    @Autowired
    private OrderTakingCommentDao orderTakingCommentDao;
    @Autowired
    private UserVipService vipService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private SysEvaluateService evaluateService;

    @Override
    public Result queryTaking(String city, String longitude, String latitude, Long userId, String like, Integer condition, Long bannerid, Long isRecommend, String id, IPage iPage, Long sex, String by, Integer classify, String salesNum) {
        Integer isVip = null;
        UserEntity userEntity = userService.getById(userId);
        String str = null;
        if (like != null) {
            str = "%" + like + "%";
        }
        if (userEntity != null) {
            UserVip userVip = vipService.getOne(new QueryWrapper<UserVip>().eq("user_id", userId));
            if (userVip != null && userVip.getIsVip() != null && userVip.getIsVip() == 1) {
                isVip = 1;
            } else {
                isVip = 2;
            }
            appSearchService.insetAppSearch(like, userId);
        }

        IPage<OrderTakingResponse> i = orderTakingDao.queryTaking(iPage, city, longitude, latitude, str, condition, bannerid, isRecommend, id, sex, by, classify, salesNum, isVip);
        return Result.success().put("data", new PageUtils(i));
    }

    @Override
    public Result queryLowTaking(Integer page, Integer limit, String city, String longitude, String latitude, Long userId, String like, Integer condition, Long bannerid, Long isRecommend, String id, Long sex, String by, Integer classify, String salesNum) {
        Integer isVip = null;
        UserEntity userEntity = userService.getById(userId);
        if (userEntity != null) {
            UserVip userVip = vipService.getOne(new QueryWrapper<UserVip>().eq("user_id", userId));
            if (userVip != null && userVip.getIsVip() != null && userVip.getIsVip() == 1) {
                isVip = 1;
            } else {
                isVip = 2;
            }
        }
        String str = null;
        if (like != null) {
            str = "%" + like + "%";
            //添加搜索记录
            appSearchService.insetAppSearch(like, userId);
        }
        if (page == null || limit == null) {
            return Result.success().put("data", orderTakingDao.queryLowTaking(city, longitude, latitude, str, condition, bannerid, isRecommend, id, sex, by, classify, salesNum, isVip));
        } else {
            return Result.success().put("data", new PageUtils(orderTakingDao.queryLowTakings(new Page<>(page, limit), city, longitude, latitude, str, condition, bannerid, isRecommend, id, sex, by, classify, salesNum, isVip)));
        }
    }


    @Override
    public Result queryTakingDetails(Long id, Long userId, String longitude, String latitude) {
        TakingDetailsResponse takingDetailsResponse = baseMapper.queryTakingDetails(id, longitude, latitude);
        if (userId!=null){
            //添加浏览足迹
            userBrowseService.addAmount(userId, takingDetailsResponse.getUserId(), id);
            //添加访客
            userBrowseService.addVisitor(userId, takingDetailsResponse.getUserId());
        }
        return Result.success().put("data", takingDetailsResponse);
    }

    @Override
    public Result queryTakingDetails(Long id, String longitude, String latitude) {
        TakingDetailsResponse takingDetailsResponse = baseMapper.queryTakingDetails(id, longitude, latitude);
        return Result.success().put("data", takingDetailsResponse);
    }

    @Override
    public Result insertOrderTaking(OrderTaking orderTaking,Integer admin) {
        CommonInfo commonInfo = commonInfoService.findOne(616);
        Game game = gameDao.selectById(orderTaking.getOrderLevel());
        UserEntity userEntity = userService.getById(orderTaking.getUserId());
        UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(userEntity.getUserId());
        if (userMoney.getSafetyMoney().compareTo(new BigDecimal(commonInfo.getValue())) < 0) {
            //508表示保证金余额不足以便前端判断是否跳转至保证金缴纳页面
            return Result.error(508, "当前账户未缴纳足额" + commonInfo.getValue() + "元的保证金");
        }

        Integer count = userCertificationDao.selectCount(new QueryWrapper<UserCertification>().eq("user_id", orderTaking.getUserId()).eq("status", 1));
        if (count != null && count > 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderTaking.setSalesNum(0);
            orderTaking.setCount(0);
            if (StringUtil.isBlank(orderTaking.getOrderTakingArea())) {
                orderTaking.setOrderTakingArea(game.getGameName());
            }
            orderTaking.setOldMoney(orderTaking.getMoney());
            //计算会员价格
            CommonInfo rateMemberInfo = commonInfoService.findOne(156);
            BigDecimal rateMember = orderTaking.getMoney().multiply(new BigDecimal(rateMemberInfo.getValue()));
            orderTaking.setMemberMoney(rateMember);
            orderTaking.setLatitude(userEntity.getLatitude());
            orderTaking.setLongitude(userEntity.getLongitude());
            //创建时间
            orderTaking.setCreateTime(simpleDateFormat.format(new Date()));
            //修改时间
            orderTaking.setUpdateTime(simpleDateFormat.format(new Date()));
            //接单状态0进行中1待审核2已取消
            if(admin==0){
                orderTaking.setStatus(1);
            }
            orderTaking.setIsdelete((long) 0);
            orderTaking.setIsRecommend("1");
            int i = baseMapper.insert(orderTaking);
            if (i > 0) {
                return Result.success("发布成功！");
            } else {
                return Result.error("发布失败！");
            }

        } else {
            return Result.error("请先进行实名认证!");
        }
    }

    @Override
    public Result selectMyRelease(Long userId, Long page, Long limit, String status) {
        if (page == null || limit == null) {
            return Result.error("分页的条件为空！");
        } else {
            Page<MyReleaseResponse> iPage = new Page<>(page, limit);
            return Result.success().put("data", new PageUtils(baseMapper.selectMyRelease(iPage, userId, status)));
        }
    }


    @Override
    public Result deleteOrderTaking(Long id) {
        if (id == null) {
            return Result.error("删除id为空");
        } else {
            int i = baseMapper.deleteById(id);
            if (i > 0) {
                return Result.success();
            } else {
                return Result.error();
            }
        }
    }

    @Override
    public Result queryAllOrderTaking(Integer page, Integer limit, String city, String gameId, Long status,
                                      String userName, Long userId, Integer classify,Integer isRecommend,String myLevel) {
        ArrayList<Long> arrayList = new ArrayList<>();
        if(StringUtil.isNotBlank(gameId)){
            Game game = gameDao.selectById(gameId);
            if (game.getParentId() == 0) {
                List<Game> gameList = gameDao.selectList(new QueryWrapper<Game>().eq("parent_id", game.getId()).eq("status", 0).orderByDesc("sort"));
                for (Game children : gameList) {
                    arrayList.add(children.getId());
                }
            } else {
                arrayList.add(game.getId());
            }

        }
        IPage<TakingResponse> iPage1 = baseMapper.queryAllOrderTaking(new Page<TakingResponse>(page, limit), city, arrayList, status,
                userName, userId, classify,isRecommend,myLevel);
        return Result.success().put("data", new PageUtils(iPage1));
    }

    @Override
    public Result auditorOrderTaking(Long id, Integer status, String content) {
        OrderTaking orderTaking = baseMapper.selectById(id);
        if (orderTaking == null) {
            return Result.error("接单信息不存在！");
        } else if (orderTaking.getStatus() != 1) {
            return Result.error("已经审核过了！");
        } else {
            orderTaking.setStatus(status);
            orderTaking.setContent(content);
            baseMapper.updateById(orderTaking);

            UserEntity userEntity = userService.selectUserById(orderTaking.getUserId());
            MessageInfo messageInfo = new MessageInfo();
            if (status == 0) {
                messageInfo.setContent("您发布的订单审核通过了");
            } else {
                messageInfo.setContent("您发布的订单审核被拒绝了，原因：" + content);
            }

            messageInfo.setTitle("发布信息审核通知");
            messageInfo.setState(String.valueOf(6));
            messageInfo.setUserName(userEntity.getUserName());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            messageInfo.setCreateAt(simpleDateFormat.format(new Date()));
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
            if (StringUtil.isNotBlank(userEntity.getClientid())) {
                userService.pushToSingle(messageInfo.getTitle(), messageInfo.getContent(), userEntity.getClientid());
            }

            return Result.success();
        }
    }

    @Override
    public Result updateTakingStatus(Long id, Integer status, String content) {
        OrderTaking orderTaking = new OrderTaking();
        orderTaking.setId(id);
        orderTaking.setStatus(status);
        orderTaking.setContent(content);
        baseMapper.updateById(orderTaking);
        return Result.success();
    }

    @Override
    public Result deleteTaking(Long id) {
        OrderTaking orderTaking = baseMapper.selectById(id);
        if (orderTaking != null) {
            orderTaking.setIsdelete((long) 1);
            baseMapper.update(orderTaking, new QueryWrapper<OrderTaking>().eq("id", id));
            return Result.success();
        } else {
            return Result.error("订单不存在！");
        }
    }

    @Override
    public Result queryTakingOrder(Long id) {
        OrderTaking orderTaking = baseMapper.selectById(id);
//        if (orderTaking != null) {
//            orderTaking.setGame(gameDao.selectById(orderTaking.getGameId()));
//        }
        return Result.success().put("data", orderTaking);
    }

    @Override
    public Result updateTakingOrder(OrderTaking orderTaking,Integer admin) {
        //计算会员价格
        CommonInfo rateMemberInfo = commonInfoService.findOne(156);
        BigDecimal rateMember = orderTaking.getMoney().multiply(new BigDecimal(rateMemberInfo.getValue()));
        orderTaking.setMemberMoney(rateMember);
        orderTaking.setUpdateTime(DateUtils.format(new Date()));
        //接单状态0进行中1待审核2已取消
        if(admin==0){
            orderTaking.setStatus(1);
        }
        baseMapper.updateById(orderTaking);
        return Result.success();
    }

    @Override
    public Result updateTakingOrders(OrderTaking orderTaking,Integer admin) {
        orderTaking.setUpdateTime(DateUtils.format(new Date()));
        if(admin==0){
            orderTaking.setStatus(1);
        }
        baseMapper.updateById(orderTaking);
        return Result.success();
    }


    @Override
    public Result queryMyTakingOrder(Long userId, Long page, Long limit, Long status) {
        Page<OrderTaking> ipage = new Page<>(page, limit);
        IPage<OrderTaking> iPage = baseMapper.selectPage(ipage, new QueryWrapper<OrderTaking>().eq("status", 0).or().eq("status", 2));
        List<OrderTaking> orderTakings = iPage.getRecords();
        for (OrderTaking orderTaking : orderTakings) {
            if (orderTaking != null) {
                QueryWrapper queryWrapper = new QueryWrapper<Orders>().eq("order_taking_id", orderTaking.getId());
                if (status != null && status != 0) {
                    queryWrapper.eq("state", status);
                }
                List<Orders> orders = ordersDao.selectList(queryWrapper);
                for (Orders order : orders) {
                    UserEntity user = userDao.selectOne(new QueryWrapper<UserEntity>().eq("user_id", order.getUserId()));
                    order.setUser(user);
                }
                orderTaking.setOrders(orders);
            }
        }
        return Result.success().put("data", iPage);
    }


    @Override
    public Result selectShopData(Long userId, String startTime, String endTime) {
        //总收益（服务收入+万能任务收入）
        BigDecimal sumOrdersMoney = ordersDao.selectOrdersMoneyByUserId(userId, null, null);
        //总销量
        int sumOrdersCount = ordersDao.selectOrdersCountByUserId(userId, null, null);
        sumOrdersCount += helpTakeDao.selectHelpTakeCount(userId, null, null);
        //用户评价
//        BigDecimal sumOrdersScore = evaluateService.selectCommentOrderScoreByUserId(userId,null,null);
        UserCertification certification = userCertificationDao.selectOne(new QueryWrapper<UserCertification>().eq("user_id", userId));
        Double score=0.0;
        if(certification!=null){
            score=certification.getScore();
        }
        //订单收入
        BigDecimal ordersMoney = ordersDao.selectOrdersMoneyByUserId(userId, startTime, endTime);
        //总订单数
        int ordersCount = ordersDao.selectOrdersCountByUserId(userId, startTime, endTime);
        ordersCount += helpTakeDao.selectHelpTakeCount(userId, startTime, endTime);
        //退款金额
        BigDecimal refundMoney = ordersDao.selectOrdersRefundMoneyByUserId(userId, startTime, endTime);
        BigDecimal refundMoneys = helpTakeDao.selectHelpTakeRefundMoneyByUserId(userId, startTime, endTime);
        refundMoney = refundMoney.add(refundMoneys);
        //访客人数
        Integer userBrowseCount = userBrowseDao.selectUserBrowseCountByUserId(userId, startTime, endTime);
        //已取消
        Integer ordersRefundCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime, 3);
        ordersRefundCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime, 4);
        //待完成
        Integer ordersUnderwayCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime, 1);
        ordersUnderwayCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime, 1);
        //已完成
        Integer ordersAccomplishCount = ordersDao.selectOrdersRefundCountByUserId(userId, startTime, endTime, 2);
        ordersAccomplishCount += helpTakeDao.selectHelpTakeRefundCountByUserId(userId, startTime, endTime, 3);
        //已评价
        Integer commentCount = evaluateService.selectCommentOrderCountByUserId(userId, startTime, endTime);
        //上架中
        Integer shangCount = orderTakingDao.selectOrderTakingCountByUserId(userId, 0);
        //已下架
        Integer xiaCount = orderTakingDao.selectOrderTakingCountByUserId(userId, 2);
        Map<String, Object> result = new HashMap<>();
        result.put("sumOrdersMoney", sumOrdersMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("sumOrdersCount", sumOrdersCount);
        result.put("sumOrdersScore", score);
        result.put("ordersMoney", ordersMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("ordersCount", ordersCount);
        result.put("refundMoney", refundMoney.setScale(2,BigDecimal.ROUND_DOWN));
        result.put("userBrowseCount", userBrowseCount);
        result.put("ordersRefundCount", ordersRefundCount);
        result.put("ordersUnderwayCount", ordersUnderwayCount);
        result.put("ordersAccomplishCount", ordersAccomplishCount);
        result.put("commentCount", commentCount);
        result.put("shangCount", shangCount);
        result.put("xiaCount", xiaCount);
        return Result.success().put("data", result);
    }


}
